package org.example.scoresystem_backen.controller;

import org.example.scoresystem_backen.common.Result;
import org.example.scoresystem_backen.dto.AuthResponse;
import org.example.scoresystem_backen.dto.StudentDTO;
import org.example.scoresystem_backen.dto.StudentWithClassDTO;
import org.example.scoresystem_backen.dto.PageRequest;
import org.example.scoresystem_backen.dto.PageResponse;
import org.example.scoresystem_backen.entity.Student;
import org.example.scoresystem_backen.entity.Class;
import org.example.scoresystem_backen.service.StudentService;
import org.example.scoresystem_backen.service.ClassService;
import org.example.scoresystem_backen.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学生控制器
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private ClassService classService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 学生登录
     *
     * @param loginRequest 登录请求
     * @return 登录结果（包含JWT令牌）
     */
    @PostMapping("/student/login")
    public Result<AuthResponse> login(@RequestBody Map<String, String> loginRequest) {
        try {
            String sno = loginRequest.get("sno");
            String password = loginRequest.get("password");
            Student student = studentService.login(sno, password);

            // 生成JWT令牌
            String token = jwtUtil.generateToken(student.getId(), student.getSno(), "student");

            // 获取班级信息
            String className = null;
            Integer classId = student.getClassId();
            if (classId != null) {
                try {
                    Class clazz = classService.findById(classId);
                    if (clazz != null) {
                        // 格式化班级名称：年级+班级名称
                        className = clazz.getGrade() + "级" + clazz.getName();
                    }
                } catch (Exception e) {
                    // 如果班级不存在，className保持为null，前端会显示"未分配"
                    System.err.println("获取班级信息失败: " + e.getMessage());
                }
            }

            // 创建认证响应（包含班级信息）
            AuthResponse authResponse = new AuthResponse(
                    token,
                    student.getId(),
                    student.getSno(),
                    "student",
                    student.getName(),
                    student.getSno(),  // studentId字段
                    classId,
                    className
            );

            return Result.success("登录成功", authResponse);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取所有学生（分页查询）
     * 支持搜索和班级过滤
     *
     * @param page 页码，从1开始
     * @param pageSize 每页大小
     * @param search 搜索关键词（学号或姓名）
     * @param classId 班级ID过滤
     * @return 学生分页数据
     */
    @GetMapping("/students")
    public Result<PageResponse<StudentWithClassDTO>> getStudents(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10", name = "page_size") Integer pageSize,
            @RequestParam(required = false) String search,
            @RequestParam(required = false, name = "class_id") Integer classId) {
        try {
            PageRequest pageRequest = new PageRequest();
            pageRequest.setPage(page);
            pageRequest.setPageSize(pageSize);
            pageRequest.setSearch(search);
            pageRequest.setClassId(classId);

            PageResponse<StudentWithClassDTO> result = studentService.findStudentsWithClassByPage(pageRequest);
            return Result.success("获取学生列表成功", result);
        } catch (Exception e) {
            return Result.error("获取学生列表失败: " + e.getMessage());
        }
    }

    /**
     * 添加学生
     *
     * @param student 学生信息
     * @return 创建结果
     */
    @PostMapping("/students")
    public Result<Student> addStudent(@RequestBody Student student) {
        try {
            Student createdStudent = studentService.createStudent(student);
            return Result.success("学生添加成功", createdStudent);
        } catch (Exception e) {
            return Result.error("添加学生失败: " + e.getMessage());
        }
    }

    /**
     * 更新学生信息
     *
     * @param id 学生ID
     * @param student 学生信息
     * @return 更新结果
     */
    @PutMapping("/students/{id}")
    public Result<Student> updateStudent(@PathVariable Integer id, @RequestBody Student student) {
        try {
            student.setId(id);
            Student updatedStudent = studentService.updateStudent(student);
            return Result.success("学生更新成功", updatedStudent);
        } catch (Exception e) {
            return Result.error("更新学生失败: " + e.getMessage());
        }
    }

    /**
     * 删除学生
     *
     * @param id 学生ID
     * @return 删除结果
     */
    @DeleteMapping("/students/{id}")
    public Result<Map<String, Object>> deleteStudent(@PathVariable Integer id) {
        try {
            Map<String, Object> result = studentService.deleteStudentWithStats(id);

            int deletedScoresCount = (Integer) result.get("deleted_scores_count");
            String message = "学生删除成功";
            if (deletedScoresCount > 0) {
                message += "，同时删除了 " + deletedScoresCount + " 条相关成绩记录";
            }

            return Result.success(message, result);
        } catch (Exception e) {
            return Result.error("删除学生失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查找学生
     *
     * @param id 学生ID
     * @return 学生信息
     */
    @GetMapping("/{id}")
    public Result<Student> findById(@PathVariable Integer id) {
        try {
            Student student = studentService.findById(id);
            return Result.success(student);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取所有学生
     *
     * @return 学生列表
     */
    @GetMapping
    public Result<List<StudentDTO>> findAll() {
        try {
            List<Student> students = studentService.findAll();
            List<StudentDTO> studentDTOs = students.stream()
                    .map(StudentDTO::new)
                    .collect(Collectors.toList());
            return Result.success(studentDTOs);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分页查询学生
     *
     * @param page 页码
     * @param size 每页大小
     * @return 学生分页数据
     */
    @GetMapping("/page")
    public Result<Page<Student>> findAllByPage(@RequestParam(defaultValue = "0") int page,
                                               @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
            Page<Student> studentPage = studentService.findAll(pageable);
            return Result.success(studentPage);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据班级ID查找学生
     *
     * @param classId 班级ID
     * @return 学生列表
     */
    @GetMapping("/class/{classId}")
    public Result<List<Student>> findByClassId(@PathVariable Integer classId) {
        try {
            List<Student> students = studentService.findByClassId(classId);
            return Result.success(students);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据姓名模糊查询学生
     *
     * @param name 姓名关键字
     * @return 学生列表
     */
    @GetMapping("/search/name")
    public Result<List<Student>> searchByName(@RequestParam String name) {
        try {
            List<Student> students = studentService.findByNameContaining(name);
            return Result.success(students);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据学号模糊查询学生
     *
     * @param sno 学号关键字
     * @return 学生列表
     */
    @GetMapping("/search/sno")
    public Result<List<Student>> searchBySno(@RequestParam String sno) {
        try {
            List<Student> students = studentService.findBySnoContaining(sno);
            return Result.success(students);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改密码
     *
     * @param passwordRequest 密码修改请求
     * @return 修改结果
     */
    @PostMapping("/change-password")
    public Result<Void> changePassword(@RequestBody Map<String, Object> passwordRequest) {
        try {
            Integer id = (Integer) passwordRequest.get("id");
            String oldPassword = (String) passwordRequest.get("oldPassword");
            String newPassword = (String) passwordRequest.get("newPassword");
            studentService.changePassword(id, oldPassword, newPassword);
            return Result.success("密码修改成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
